from PyQt4 import QtGui

from fogmini.data import AssignedCasesModel, Case

class TrayMenu(QtGui.QMenu):
    def __init__(self, *args, **kwargs):
        QtGui.QMenu.__init__(self, *args, **kwargs)

        self.aboutToShow.connect(self.populate)

    def populate(self):
        self.clear()

        startWorkLabelAction = QtGui.QWidgetAction(self)
        startWorkLabelAction.setDefaultWidget(QtGui.QLabel("Start Working On:"))
        startWorkLabel = self.addAction(startWorkLabelAction)

        startWorkEditAction = StartWorkWidgetAction(self)
        startWorkEdit = self.addAction(startWorkEditAction)

        self.addSeparator()

        exitAction = self.addAction("Exit")
        exitAction.triggered.connect(self.exit)

    def exit(self):
        QtGui.QApplication.quit()

class StartWorkWidgetAction(QtGui.QWidgetAction):
    def createWidget(self, parent):
        lineedit = QtGui.QLineEdit(parent)
        lineedit.model = AssignedCasesModel()
        lineedit.completer = QtGui.QCompleter(lineedit.model, lineedit)
        lineedit.setCompleter(lineedit.completer)

        lineedit.editingFinished.connect(self.start_working(lineedit))

        return lineedit

    def start_working(self, lineedit):
        def f():
            lineedit.completer.popup().setVisible(False)
            global_objects.tray.contextMenu().setVisible(False)

            bugname = lineedit.text()

            if ":" in bugname:
                bugname = bugname.split(":")[0]

            try:
                global_objects.fb.startWork(ixbug=bugname)
            except FogBugzAPIError, e:
                global_objects.tray.showMessage("Can't Start Working", unicode(e), 5000)
            else:
                case = Case.search(q=str(bugname))

                global_objects.tray.showMessage("Started Working", "Working on %s (%i)" % (case.title, case.id), 5000)

        return f
